import {FORM_CONFIG} from "../config/Config"
import {request,myFetch} from "../utils/request"
import {checkResult} from "./init"
import {isNull} from "../utils/helper"
export default {
	
	namespace:'page',
	
	state:{
	},
	
	subscriptions:{},
	
	effects:{
		*getFC({payload,type,action},{call,put,select}){
			const {callback,_c,formDataKey}  = payload;
			let apiInfo={
				url:FORM_CONFIG+"?_c="+_c,
				page_enable:0,
				params:[]
			};
			let data={};
			let result = yield call(request,{apiInfo,data});
			if(checkResult(result)){
				yield put({
					type:"setStateByKey",
					payload:{
						key:formDataKey,
						value:{
							config:result.data
						}
					}
				});
				callback(result.data)
			}
			else{
				callback&&callback({...result,error:true})
			}
		},
		*getDataSource({payload,type,action},{call,put,select}){
			let {apiInfo,data,dataset_key,options=[],source_type,formDataKey,pager,callback,tabs_id} = payload;
			yield put({type:"setStateFd",payload:{formDataKey,value:{[dataset_key+"Loading"]:true}}});
			if(source_type=="server"){
				let result = yield call(myFetch,{apiInfo,data,pager});
				if(checkResult(result,null,null,false)){
					options=options.concat(result.data)
				}
			}
			callback&&callback(options);
			yield put({type:"setStateFd",payload:{formDataKey,value:{[dataset_key]:options}}});
			yield put({type:"setStateFd",payload:{formDataKey,value:{[dataset_key+"Loading"]:false}}});
			if(!isNull(tabs_id)){
				yield put({
					type:"setStateFd",
					payload:{
						formDataKey,value:{[tabs_id]:options[0].stat}
					}
				})
			}
		}
	},
	
	reducers:{
		setState(state,action){
			return {
				...state,...action.payload
			}
		},
		setStateByKey(state,{payload}){
			let {key,value}=payload;
			let oldState=state[key];
			let obj={
				[key]:{
					...oldState,
					...value
				}
			};
			return {
				...state,
				...obj
			}
		},
		setStateFd(state,action){
			let {formDataKey,value} = action.payload;
			return {
				...state,
				[formDataKey]:{
					...state[formDataKey],
					...value
				}
			}
		},
		removeState(state,{payload}){
			let {formDataKey}=payload;
			delete state[formDataKey];
			return {
				...state
			}
		},
		setFormData(state,action){
			const {payload}=action;
			const {key,value}=payload;
			if(state[key]){
				return {
					...state,
					[key]:{
						...state[key],
						formData:{
							...state[key].formData,
							...value
						}
					}
				}
			}
			else{
				return {
					...state,
					[key]:{
						formData:{
							...value
						}
					}
				}
			}
		}
	}
	
};
